package cn.com.headfree.workflowant.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;

import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.gta.edu.sdk.base.service.impl.BaseServiceImpl;
import com.gta.edu.sdk.common.dto.Page;
import com.gta.edu.sdk.util.IdGen;

import cn.com.headfree.base.controller.ResultData;
import cn.com.headfree.call.IHumanManageUserInfoServerCall;
import cn.com.headfree.entity.TBusinessWorkflowBind;
import cn.com.headfree.entity.TMouldInfo;
import cn.com.headfree.entity.TOrgDept;
import cn.com.headfree.entity.TRecordOptLog;
import cn.com.headfree.entity.TSysDictionaryInfo;
import cn.com.headfree.entity.isc.User;
import cn.com.headfree.recordlog.service.IRecordLogService;
import cn.com.headfree.vo.workflow.ProcessListVo;
import cn.com.headfree.workflowant.dao.IWorkFlowAntDao;
import cn.com.headfree.workflowant.dto.ApproveWorkFlowDto;
import cn.com.headfree.workflowant.dto.BusinessWorkFlowDto;
import cn.com.headfree.workflowant.dto.WorkFlowCount;
import cn.com.headfree.workflowant.service.IWorkFlowAntService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**  
 * @Title  WorkFlowAntServiceImpl.java   
 * @Package cn.com.headfree.workflowant.service.impl   
 * @Description 流程serviceImpl
 * @author yangwang 
 * @date  2020年7月29日 下午5:39:04   
 */
@Service("workFlowAntService")
public class WorkFlowAntServiceImpl extends BaseServiceImpl<ApproveWorkFlowDto> implements IWorkFlowAntService {
	private static final Logger LOG = LogManager.getLogger(WorkFlowAntServiceImpl.class);
	
	@Value("${comm.sys.code}")
	private String COMM_SYS_CODE;
	@Value("${comm.sys.domain.id}")
	private String COMM_SYS_DOMAIN_ID;
	@Autowired
	private IWorkFlowAntDao workFlowAntDao;
	@Autowired
	private IHumanManageUserInfoServerCall humanManageUserInfoServerCall;
	//操作记录
	@Autowired
	private IRecordLogService recordLogService;

	/**
	 * 获取所有一级单位
	 * @author yangwang
	 * @return  List<TOrgDept>
	 *  */
	@Override
	public List<TOrgDept> getWorkFlowUnits(){
		return workFlowAntDao.getWorkFlowUnits();
	}
	
	/**
	 * 获取所有业务类型
	 * @author yangwang
	 * @return  List<TMouldInfo>
	 *  */
	@Override
	public List<TMouldInfo> getMouldInfoList(){
		return workFlowAntDao.getMouldInfoList(null);
	}
	

	/**
	 * 获取当前人待办/已办业务类型
	 * @author yangwang
	 * @param erpNo erp编码
	 * @param status (0-待审核,1-通过,2-不通过,3-驳回，-1-全部)
	 * @return  List<TMouldInfo>
	 *  */
	@Override
	public List<TMouldInfo> getMouldsOfUser(ProcessListVo process){
		List<TMouldInfo> moduleList = workFlowAntDao.getMouldInfoList((null != process)?process.getBusinessTypeId():null);
		if((null != moduleList)&&(0 < moduleList.size())) {
	        Iterator<TMouldInfo> it = moduleList.iterator();
	        TMouldInfo module = null;
	        WorkFlowCount count = null;
	        while (it.hasNext()) {
	        	module = it.next();
	            if ((null != module)&&(StringUtils.isNotBlank(module.getId()))&&(StringUtils.isNotBlank(module.getTabName()))) {
	            	//获取业务流程统计
	            	count = workFlowAntDao.getBusinessFlowCount(module.getTabName(), process);
	            	module.setModuleCount(count.getFlowCount());
	            	if(!((null != count)&&(0 < count.getFlowCount()))) {
	            		it.remove();//使用迭代器的删除方法删除
	            	}
	            }
	        }
			
			return moduleList;
		}
		return new ArrayList<TMouldInfo>();
	}
	
	/**
	 * 获取系统配置的工作流模板
	 * @author yangwang
	 * @return ResultData
	 * @throws Exception 
	 *  */
	@Override
	public ResultData getWorkFlowTemplates() throws Exception {
		ResultData result = new ResultData();
		
		try {
			result = humanManageUserInfoServerCall.findWorkFlowsBySysCode(COMM_SYS_CODE);
			LOG.info("根据系统编码获取该系统下所有的工作流接口返回数据为--"+JSON.toJSONString(result));
		} catch (Exception e) {
			e.printStackTrace();
			LOG.error("根据系统编码获取工作流列表出现异常",e);
			result.setSuccess(false);
			result.setErrorMsg("根据系统编码获取工作流列表出现异常");
			throw new Exception("根据系统编码获取工作流列表出现异常");
		}
		
		return result;
	}
	
	/**
	 * 更新流程绑定
	 * @author yangwang
	 * @param bind 绑定信息
	 *  */
	@Transactional
	@Override
	public void updateWorkFlowBind(TBusinessWorkflowBind bind) {
		TBusinessWorkflowBind old = workFlowAntDao.getWorkFlowBind(bind);
		if((null != old)&&(StringUtils.isNotBlank(old.getId()))) {
			bind.setId(old.getId());
			workFlowAntDao.updateWorkFlowBind(bind);
		}else {
			bind.setId(IdGen.uuid());
			workFlowAntDao.insertWorkFlowBind(bind);
		}
	}
	
	/**
	 * 添加业务流程
	 * @author yangwang
	 * @param token 请求token
	 * @param user 统一权限用户
	 * @param businessTypeId 业务类型id
	 * @param businessId 业务id
	 * @param approveAdvise 审批意见
	 * @param approveCondition 审批条件
	 * @return ResultData
	 *  */
	@Transactional
	@Override
	public ResultData addWorkFlow(User user,String businessTypeId,String businessId,String approveAdvise,String approveCondition) {
		LOG.info("添加业务流程开始--start");
		ResultData result = new ResultData();

		if(StringUtils.isNotBlank(COMM_SYS_DOMAIN_ID)) {
			if((null != user)&&(StringUtils.isNotBlank(user.getId()))) {
				if(StringUtils.isNotBlank(businessTypeId)) {
					if(StringUtils.isNotBlank(businessId)) {
						TMouldInfo module = workFlowAntDao.getMouldInfoById(businessTypeId);
						if((null != module)&&(StringUtils.isNotBlank(module.getId()))) {
							TBusinessWorkflowBind bind = workFlowAntDao.getWorkFlowBind(new TBusinessWorkflowBind(module.getId(),user.getBaseOrgId()));
							LOG.info("流程绑定信息为--"+JSON.toJSONString(bind));
							if((null != bind)&&(StringUtils.isNotBlank(bind.getId()))&&(StringUtils.isNotBlank(bind.getFlowId()))) {
								try {
									result = humanManageUserInfoServerCall.saveApproveRecord(bind.getFlowId(), businessId, approveCondition, user.getId(), approveAdvise, COMM_SYS_DOMAIN_ID);
									LOG.info("提交工作流接口返回数据为--"+JSON.toJSONString(result));
									if (result.isSuccess()) {
										if (result.getData().equals(true)) {
											result.setData(1);
										} else {
											result.setData(0);
										}
										LOG.info("提交流程成功");
									}else {
										LOG.error("提交流程失败");
										result.setSuccess(false);
										result.setErrorMsg("提交流程失败");
									}
								}catch (Exception e) {
									e.printStackTrace();
									LOG.error("提交流程调用comm-work-flow-server组件的接口失败",e);
									result.setSuccess(false);
									result.setErrorMsg("提交流程调用comm-work-flow-server组件的接口失败");
								}
							}else {
								LOG.error("当前业务类型未绑定流程模板,不可提交流程");
								result.setSuccess(false);
								result.setErrorMsg("当前业务类型未绑定流程模板,不可提交流程");
							}
						}else {
							LOG.error("当前业务类型不存在");
							result.setSuccess(false);
							result.setErrorMsg("当前业务类型不存在");
						}
					}else {
						LOG.error("业务businessId不可为空");
						result.setSuccess(false);
						result.setErrorMsg("业务businessId不可为空");
					}
				}else {
					LOG.error("业务类型businessTypeId不可为空");
					result.setSuccess(false);
					result.setErrorMsg("业务类型businessTypeId不可为空");
				}
			}else {
				LOG.error("统一权限iscUserId不可为空");
				result.setSuccess(false);
				result.setErrorMsg("统一权限iscUserId不可为空");
			}
		}else {
			LOG.error("当前系统业务域id不可为空");
			result.setSuccess(false);
			result.setErrorMsg("当前系统业务域id不可为空");
		}
		LOG.info("添加业务流程结束--end");
		return result;
	}
	
	/**
	 * 审批业务流程
	 * @author yangwang
	 * @param token 请求token
	 * @param user 统一权限用户
	 * @param businessTypeId 业务类型id
	 * @param businessId 业务id
	 * @param approveId 审批节点id
	 * @param approveResult 审批状态(1-通过,2-不通过)
	 * @param approveAdvise 审批意见
	 * @param approveCondition 审批条件
	 * @return ResultData
	 *  */
	@Transactional
	@Override
	public ResultData approveWorkFlow(User user,ApproveWorkFlowDto flowDto) {
		ResultData result = new ResultData();
		
		if(StringUtils.isNotBlank(COMM_SYS_DOMAIN_ID)) {
			if(StringUtils.isNotBlank(flowDto.getApproveId())) {
				try {
					System.out.println("审批流程请求数据为--"+JSON.toJSONString(flowDto));
					LOG.info("审批流程请求数据为--"+JSON.toJSONString(flowDto));
					result = humanManageUserInfoServerCall.approveRecord(flowDto.getApproveId(), flowDto.getApproveAdvise(), flowDto.getIscUserId(), COMM_SYS_DOMAIN_ID, flowDto.getApproveCondition());
					System.out.println("审批流程接口返回数据为--"+JSON.toJSONString(result));
					LOG.info("审批流程接口返回数据为--"+JSON.toJSONString(result));
					if (result.isSuccess()) {
						TMouldInfo module = workFlowAntDao.getMouldInfoById(flowDto.getBusinessTypeId());
						if((null != module)&&(StringUtils.isNotBlank(module.getId()))) {
							BusinessWorkFlowDto businessDto = new BusinessWorkFlowDto();
							businessDto.setErpNo(flowDto.getCurrentLoginErpNo());
							businessDto.setUserName(flowDto.getUserName());
							businessDto.setTabName(module.getTabName());
							businessDto.setBusinessId(flowDto.getBusinessId());
							businessDto.setDealTime(new Date());
							businessDto.setFolwStatus(flowDto.getApproveResult());
							workFlowAntDao.updateBusinessWorkFlowStatus(businessDto);
							//获取业务信息
							ApproveWorkFlowDto businessMsg = workFlowAntDao.getBusinessDataByParams(module.getTabName(), flowDto.getBusinessId());
							if((null != businessMsg)&&(StringUtils.isNotBlank(businessMsg.getBusinessId()))) {
								//更新上一条记录为无效
								if(!StringUtils.equals(businessMsg.getBusinessId(), businessMsg.getOrignalId())) {
									workFlowAntDao.updateBusinessIsValid(businessDto);
								}
								flowDto.setPrimitiveId(businessMsg.getPrimitiveId());
							}
							//添加操作记录
							if(!((0 == flowDto.getApproveResult())||(1 == flowDto.getApproveResult()))) {
								this.addRecordLogData(user, module,flowDto);
							}
						}
						LOG.info("提交流程成功");
					}else {
						LOG.error("提交流程失败");
						result.setSuccess(false);
						result.setErrorMsg("提交流程失败");
					}
				}catch (Exception e) {
					e.printStackTrace();
					LOG.error("审批流程调用comm-work-flow-server组件的接口失败",e);
					result.setSuccess(false);
					result.setErrorMsg("审批流程调用comm-work-flow-server组件的接口失败");
				}
			}else {
				LOG.error("审批节点approveId不可为空");
				result.setSuccess(false);
				result.setErrorMsg("审批节点approveId不可为空");
			}
		}else {
			LOG.error("当前系统业务域id不可为空");
			result.setSuccess(false);
			result.setErrorMsg("当前系统业务域id不可为空");
		}
		
		return result;
	}
	
	/**
	 * 插入操作记录
	 * @param businessId 业务id
	 * @param user 统一权限用户
	 * @param mouldName 类型名称
	 * @param approveResult 审批状态(1-通过,2-不通过,3-驳回)
	 * @param approveAdvise 审批意见
	 */
	public void addRecordLogData(User user,TMouldInfo module,ApproveWorkFlowDto flowDto){
		//插入操作记录
		LOG.info("插入操作记录之前,必要参数为:"+JSON.toJSONString(flowDto));
		TRecordOptLog log = new TRecordOptLog();
		log.setRecordId(flowDto.getPrimitiveId());
		log.setCurrentRecordId(flowDto.getBusinessId());
		log.setOptStatus(flowDto.getApproveResult());
		ApproveWorkFlowDto businessDto = workFlowAntDao.getBusinessDataByParams(module.getTabName(), flowDto.getBusinessId());
		switch(flowDto.getApproveResult()) {
			case 0:
				log.setOptType("2");
				log.setOptContent(user.getName()+"提交"+module.getMouldName()+"流程");
				break;
			case 1:
				log.setOptType("6");
				log.setOptContent(user.getName()+"审核通过"+(StringUtils.isNotBlank(businessDto.getUserName())?businessDto.getUserName():"")+"提交的"+module.getMouldName()+(StringUtils.isNotBlank(flowDto.getApproveAdvise())?(",审核意见:"+flowDto.getApproveAdvise()):""));
				break;
			case 2:
				log.setOptType("10");
				log.setOptContent(user.getName()+"审核不通过"+(StringUtils.isNotBlank(businessDto.getUserName())?businessDto.getUserName():"")+"提交的"+module.getMouldName()+(StringUtils.isNotBlank(flowDto.getApproveAdvise())?(",审核意见:"+flowDto.getApproveAdvise()):""));
				break;
			case 3:
				log.setOptType("8");
				log.setOptContent(user.getName()+"审核驳回"+(StringUtils.isNotBlank(businessDto.getUserName())?businessDto.getUserName():"")+"提交的"+module.getMouldName()+(StringUtils.isNotBlank(flowDto.getApproveAdvise())?(",审核意见:"+flowDto.getApproveAdvise()):""));
				break;
			default:
				log.setOptContent(user.getName()+"进行了未知操作");
				break;
		}
		LOG.info("即将插入操作记录数据为:"+JSON.toJSONString(log));
		recordLogService.save(user,log);
	}

	/**
	 * 获取待办业务流程数据
	 * @author yangwang
	 * @param page 分页参数
	 * @param user 统一权限用户
	 * @return ResultData
	 *  */
	@SuppressWarnings({ "deprecation", "unchecked" })
	@Override
	public ResultData getWaitApproveWorkFlows(Page<ApproveWorkFlowDto> page,User user) {
		ResultData result = new ResultData();
		
		if((null != user)&&(StringUtils.isNotBlank(user.getId()))) {
			try {
				result = this.humanManageUserInfoServerCall.findWaitApproveWorkFlow(COMM_SYS_CODE,user.getId(), page.getPageSize(), page.getPageNo());
				LOG.info("分页查找系统编码下所有待审批任务接口返回数据为--"+JSON.toJSONString(result));
				if (result.isSuccess()) {
					if(null != result.getData()) {
						JSONObject resultData = JSONObject.fromObject(result.getData());
						if(null != resultData) {
							page.setTotalCount(resultData.getInt("totalCount"));
							List<ApproveWorkFlowDto> flowList = new ArrayList<ApproveWorkFlowDto>();
							JSONArray resultArray = resultData.getJSONArray("result");
							if((null != resultArray)&&(0 < resultArray.size())) {
								flowList = JSONArray.toList(resultArray, ApproveWorkFlowDto.class);
								if((null != flowList)&&(0 < flowList.size())) {
									TMouldInfo moduleInfo = null;
									ApproveWorkFlowDto businessMsg = null;
									List<TOrgDept> deptList = null;
									List<TBusinessWorkflowBind> bindList = null;
									//获取流程状态
									List<TSysDictionaryInfo> dicList = workFlowAntDao.getDictionarys("FlowAuditStatus");
									for(ApproveWorkFlowDto dto:flowList) {
										if((StringUtils.isNotBlank(dto.getWorkFlowId()))&&(StringUtils.isNotBlank(dto.getBusinessId()))) {
											dto.setBusinessId(dto.getBusinessId());
											//获取流程绑定信息
											bindList = workFlowAntDao.getWorkflowBindByOrgAndFlowId(user.getBaseOrgId(), dto.getWorkFlowId());
											if((null != bindList)&&(0 < bindList.size())) {
												dto.setMouldId(bindList.get(0).getBusinessTypeId());
												moduleInfo=workFlowAntDao.getMouldInfoById(bindList.get(0).getBusinessTypeId());
												if((null != moduleInfo)&&(StringUtils.isNotBlank(moduleInfo.getId()))) {
													dto.setMouldName(moduleInfo.getMouldName());
													dto.setTabName(moduleInfo.getTabName());
													businessMsg = workFlowAntDao.getBusinessDataByParams(moduleInfo.getTabName(), dto.getBusinessId());
													if((null != businessMsg)&&(StringUtils.isNotBlank(businessMsg.getBusinessId()))) {
														dto.setErpNo(businessMsg.getErpNo());
														dto.setCurrentLoginRoleCode(businessMsg.getErpNo());
														dto.setUserName(businessMsg.getUserName());
														dto.setDealTime(businessMsg.getDealTime());
														dto.setHandleTime(businessMsg.getHandleTime());
														dto.setPrimitiveId(businessMsg.getPrimitiveId());
														//获取部门信息
														deptList = workFlowAntDao.getDeptByErpNo(businessMsg.getErpNo());
														if((null != deptList)&&(0 < deptList.size())) {
															dto.setDeptId(deptList.get(0).getId());
															dto.setDeptName(deptList.get(0).getName());
														}
														//设置流程状态名称
														if(null != businessMsg.getFlowStatus()) {
															Integer flowStatus = businessMsg.getFlowStatus();
															if((null != dicList)&&(0 < dicList.size())) {
																if(null != businessMsg.getFlowStatus()) {
																	Optional<TSysDictionaryInfo> opt = dicList.stream().filter(d -> ((null !=d)&&(StringUtils.isNotBlank(d.getValue()))&&(StringUtils.equals(d.getValue(), String.valueOf(flowStatus))))).findFirst();
																	if(opt.isPresent()) {
																		dto.setFlowStatusName(opt.get().getName());
																	}
																}
															}		
														}
													}
												}
											}
										}
									}
								}
							}
							//按提报时间倒叙
							if((null != flowList)&&(0 < flowList.size())) {
								flowList.sort((f, t) -> {
									if(null!=t.getDealTime()&&null!=f.getDealTime()) {
										return t.getDealTime().compareTo(f.getDealTime());
									}else {
										return -1;
									}
				                });
							}
							page.setResult(flowList);
							result.setData(page);
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
				LOG.error("获取待审批流程调用comm-work-flow-server组件的接口失败",e);
				result.setSuccess(false);
				result.setErrorMsg("获取待审批流程调用comm-work-flow-server组件的接口失败");
			}
		}else {
			LOG.error("统一权限iscUserId不可为空");
			result.setSuccess(false);
			result.setErrorMsg("统一权限iscUserId不可为空");
		}
		
		return result;
	}
	
	/**
	 * 获取已办业务流程数据
	 * @author yangwang
	 * @param page 分页参数
	 * @param user 统一权限用户
	 * @return ResultData
	 *  */
	@SuppressWarnings({ "unchecked", "deprecation" })
	@Override
	public ResultData getDoneApproveWorkFlows(Page<ApproveWorkFlowDto> page,User user) {
		ResultData result = new ResultData();
		
		if((null != user)&&(StringUtils.isNotBlank(user.getId()))) {
			try {
				result = this.humanManageUserInfoServerCall.findApprovedWorkFlow(COMM_SYS_CODE,user.getId(), page.getPageSize(), page.getPageNo());
				LOG.info("分页查找系统编码下所有已审批任务接口返回数据为--"+JSON.toJSONString(result));
				if (result.isSuccess()) {
					if(null != result.getData()) {
						JSONObject resultData = JSONObject.fromObject(result.getData());
						if(null != resultData) {
							page.setTotalCount(resultData.getInt("totalCount"));
							List<ApproveWorkFlowDto> flowList = new ArrayList<ApproveWorkFlowDto>();
							JSONArray resultArray = resultData.getJSONArray("result");
							if((null != resultArray)&&(0 < resultArray.size())) {
								flowList = JSONArray.toList(resultArray, ApproveWorkFlowDto.class);
								if((null != flowList)&&(0 < flowList.size())) {
									TMouldInfo moduleInfo = null;
									ApproveWorkFlowDto businessMsg = null;
									List<TOrgDept> deptList = null;
									List<TBusinessWorkflowBind> bindList = null;
									//获取流程状态
									List<TSysDictionaryInfo> dicList = workFlowAntDao.getDictionarys("FlowAuditStatus");
									for(ApproveWorkFlowDto dto:flowList) {
										if((StringUtils.isNotBlank(dto.getWorkFlowId()))&&(StringUtils.isNotBlank(dto.getBusinessId()))) {
											dto.setBusinessId(dto.getBusinessId());
											//获取流程绑定信息
											bindList = workFlowAntDao.getWorkflowBindByOrgAndFlowId(user.getBaseOrgId(), dto.getWorkFlowId());
											if((null != bindList)&&(0 < bindList.size())) {
												dto.setMouldId(bindList.get(0).getBusinessTypeId());
												moduleInfo=workFlowAntDao.getMouldInfoById(bindList.get(0).getBusinessTypeId());
												if((null != moduleInfo)&&(StringUtils.isNotBlank(moduleInfo.getId()))) {
													dto.setMouldName(moduleInfo.getMouldName());
													dto.setTabName(moduleInfo.getTabName());
													businessMsg = workFlowAntDao.getBusinessDataByParams(moduleInfo.getTabName(), dto.getBusinessId());
													if((null != businessMsg)&&(StringUtils.isNotBlank(businessMsg.getBusinessId()))) {
														dto.setUserName(businessMsg.getUserName());
														dto.setErpNo(businessMsg.getErpNo());
														dto.setCurrentLoginRoleCode(businessMsg.getErpNo());
														dto.setDealTime(businessMsg.getDealTime());
														dto.setHandleTime(businessMsg.getHandleTime());
														dto.setPrimitiveId(businessMsg.getPrimitiveId());
														//获取部门信息
														deptList = workFlowAntDao.getDeptByErpNo(businessMsg.getErpNo());
														if((null != deptList)&&(0 < deptList.size())) {
															dto.setDeptId(deptList.get(0).getId());
															dto.setDeptName(deptList.get(0).getName());
														}
														//设置流程状态名称
														if(null != businessMsg.getFlowStatus()) {
															Integer flowStatus = businessMsg.getFlowStatus();
															if((null != dicList)&&(0 < dicList.size())) {
																if(null != businessMsg.getFlowStatus()) {
																	Optional<TSysDictionaryInfo> opt = dicList.stream().filter(d -> ((null !=d)&&(StringUtils.isNotBlank(d.getValue()))&&(StringUtils.equals(d.getValue(), String.valueOf(flowStatus))))).findFirst();
																	if(opt.isPresent()) {
																		dto.setFlowStatusName(opt.get().getName());
																	}
																}
															}		
														}
													}
												}
											}
										}
									}
								}
							}
							//按办理时间倒叙
							if((null != flowList)&&(0 < flowList.size())) {
								flowList.sort((f, t) -> {
									if(null!=t.getHandleTime()&&null!=f.getHandleTime()) {
										return t.getHandleTime().compareTo(f.getHandleTime());
									}else {
										return -1;
									}
								});
							}
							page.setResult(flowList);
							result.setData(page);
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
				LOG.error("获取已审批流程调用comm-work-flow-server组件的接口失败",e);
				result.setSuccess(false);
				result.setErrorMsg("获取已审批流程调用comm-work-flow-server组件的接口失败");
			}
		}else {
			LOG.error("统一权限iscUserId不可为空");
			result.setSuccess(false);
			result.setErrorMsg("统一权限iscUserId不可为空");
		}
		
		return result;
	}
	
	/**
	 * 获取下一审批节点数据
	 * @author yangwang
	 * @param approveId 审批id
	 * @return ResultData
	 *  */
	@Override
	public ResultData getNextWorkFlowConditions(String approveId) {
		ResultData result = new ResultData();
		
		if(StringUtils.isNotBlank(approveId)) {
			try {
				result = humanManageUserInfoServerCall.getNextWorkFlowCondition(approveId);
				LOG.info("根据审批ID获取流程该节点审批条件接口返回数据为--"+JSON.toJSONString(result));
				if((result.isSuccess())&&(null == result.getData())) {//构造业务按钮
					String jsonStr = "[{\"handleResult\":\"通过\",\"handleResultValue\":\"1\",\"toNode\":\"end\",\"nodeName\":\"结束\"},{\"handleResult\":\"不通过\",\"handleResultValue\":\"2\",\"toNode\":\"end\",\"nodeName\":\"结束\"},{\"handleResult\":\"驳回\",\"handleResultValue\":\"3\",\"toNode\":\"end\",\"nodeName\":\"结束\"}]";
					JSONArray jsonArr = JSONArray.fromObject(jsonStr);
					result.setData(jsonArr);
				}
			}catch (Exception e) {
				e.printStackTrace();
				LOG.error("根据审批ID获取流程审批数据调用comm-work-flow-server组件的接口失败",e);
				result.setSuccess(false);
				result.setErrorMsg("根据审批ID获取流程审批数据调用comm-work-flow-server组件的接口失败");
			}
		}else {
			LOG.error("审批approveId不可为空");
			result.setSuccess(false);
			result.setErrorMsg("审批approveId不可为空");
		}
		
		return result;
	}
	
	/**
	 * 获取审核进度列表数据
	 * @author yangwang
	 * @param page 分页
	 * @param process 进度数据
	 *  @param user 统一权限用户
	 * @return ResultData
	 *  */
	@Override
	public ResultData approveProcessPage(Page<ProcessListVo> page,ProcessListVo process,User user) {
		ResultData result = new ResultData();
		
		//根据类型id获取类型相关信息
		TMouldInfo moduleInfo=workFlowAntDao.getMouldInfoById(process.getBusinessTypeId());
		if((null != moduleInfo)&&(StringUtils.isNotBlank(moduleInfo.getId()))) {
			process.setTabName(moduleInfo.getTabName());
			process.setBusinessTypeName(moduleInfo.getMouldName());
			//获取流程进度信息
			workFlowAntDao.approveProcessPage(page, process);
			if((null != page)&&(null != page.getResult())&&(0 < page.getResult().size())) {
				//根据单位和业务类型获取流程绑定信息
				TBusinessWorkflowBind bind = workFlowAntDao.getWorkFlowBind(new TBusinessWorkflowBind(process.getBusinessTypeId(),user.getBaseOrgId()));
				if((null != bind)&&(StringUtils.isNotBlank(bind.getId()))) {
					process.setId(bind.getFlowId());
				}
				//获取流程状态
				List<TSysDictionaryInfo> dicList = workFlowAntDao.getDictionarys("FlowAuditStatus");
				//遍历处理数据
				for(ProcessListVo plv:page.getResult()) {
					if((null != plv)&&(StringUtils.isNotBlank(plv.getBusinessId()))) {
						if((null != dicList)&&(0 < dicList.size())) {
							if(null != plv.getFlowStatus()) {
								Optional<TSysDictionaryInfo> opt = dicList.stream().filter(d -> ((null !=d)&&(StringUtils.isNotBlank(d.getValue()))&&(StringUtils.equals(d.getValue(), String.valueOf(plv.getFlowStatus()))))).findFirst();
								if(opt.isPresent()) {
									plv.setFlowStatusName(opt.get().getName());
								}
							}
						}
						//若为待审核，则审核时间为空
						if(0 == plv.getFlowStatus()) {
							plv.setUpdateTime(null);
						}
						plv.setId(process.getId());
						plv.setBusinessTypeId(process.getBusinessTypeId());
						plv.setBusinessTypeName(process.getBusinessTypeName());
						plv.setDealErpNo(process.getDealErpNo());
						plv.setTabName(process.getTabName());
					}
				}
			}
			result.setData(page);
		}else{
			LOG.error("当前业务类型不存在");
			result.setSuccess(false);
			result.setErrorMsg("当前业务类型不存在");
		}
		
		return result;
	}
	
	/**
	 * 根据业务ID获取该业务的审批记录
	 * @author yangwang
	 * @param businessId 业务id
	 * @return ResultData
	 * @throws Exception 
	 */
	@Override
	public ResultData findApprovedRecord(String businessId) throws Exception {
		ResultData result = new ResultData();
		
		try {
			result = humanManageUserInfoServerCall.findApprovedRecord(businessId);
		} catch (Exception e) {
			e.printStackTrace();
			LOG.error("根据业务ID获取该业务的审批记录异常",e);
			result.setSuccess(false);
			result.setErrorMsg("根据业务ID获取该业务的审批记录异常");
			throw new Exception("根据业务ID获取该业务的审批记录异常");
		}
		
		return result;
	}
	
	/**
	 * 删除业务
	 * @author yangwang
	 * @param user 统一权限用户
	 * @param process
	 *  */
	@Transactional
	@Override
	public ResultData deleteBusiness(User user,ProcessListVo process) {
		ResultData result = new ResultData();
		
		if((null != user)&&(StringUtils.isNotBlank(user.getId()))) {
			if(StringUtils.isNotBlank(process.getBusinessTypeId())) {
				if(StringUtils.isNotBlank(process.getBusinessId())) {
					try {
						//根据类型id获取类型相关信息
						TMouldInfo moduleInfo=workFlowAntDao.getMouldInfoById(process.getBusinessTypeId());
						if((null != moduleInfo)&&(StringUtils.isNotBlank(moduleInfo.getId()))) {
							process.setTabName(moduleInfo.getTabName());
							workFlowAntDao.deleteBusiness(user, process);
						}else{
							LOG.error("当前业务类型不存在");
							result.setSuccess(false);
							result.setErrorMsg("当前业务类型不存在");
						}
					} catch (Exception e) {
						e.printStackTrace();
						LOG.error("删除业务异常",e);
						result.setSuccess(false);
						result.setErrorMsg("删除业务异常");
					}
				}else {
					LOG.error("业务businessId不可为空");
					result.setSuccess(false);
					result.setErrorMsg("业务businessId不可为空");
				}
			}else {
				LOG.error("业务类型businessTypeId不可为空");
				result.setSuccess(false);
				result.setErrorMsg("业务类型businessTypeId不可为空");
			}
		}else {
			LOG.error("统一权限iscUserId不可为空");
			result.setSuccess(false);
			result.setErrorMsg("统一权限iscUserId不可为空");
		}

		return result;
	}

	@Override
	public ResultData test(String sysCode) {
		ResultData result=new ResultData();
		System.out.println("准备调用公共框架。。。");
		result = humanManageUserInfoServerCall.findWorkFlowsBySysCode(sysCode);
		System.out.println("公共框架调用结束。。。");
		return result;
	}
	
}
